package com.lidroid.xutils.sample.fragment;

import java.io.File;

import org.apache.http.impl.cookie.BasicClientCookie;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.DbException;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.HttpHandler;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.ResponseStream;
import com.lidroid.xutils.http.HttpHandler.State;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.lidroid.xutils.sample.DownloadListActivity;
import com.lidroid.xutils.sample.R;
import com.lidroid.xutils.sample.download.DownloadInfo;
import com.lidroid.xutils.sample.download.DownloadManager;
import com.lidroid.xutils.sample.download.DownloadService;
import com.lidroid.xutils.util.LogUtils;
import com.lidroid.xutils.util.PreferencesCookieStore;
import com.lidroid.xutils.view.ResType;
import com.lidroid.xutils.view.annotation.ResInject;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.lidroid.xutils.view.annotation.event.OnClick;

/**
 * Author: wyouflf
 * Date: 13-9-14
 * Time: 下午3:35
 */
public class HttpFragment extends Fragment {

    //private HttpHandler handler;

    private Context mAppContext;
    private DownloadManager downloadManager;

    private PreferencesCookieStore preferencesCookieStore;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.http_fragment, container, false);
        ViewUtils.inject(this, view);

        mAppContext = inflater.getContext().getApplicationContext();

        downloadManager = DownloadService.getDownloadManager(mAppContext);

        preferencesCookieStore = new PreferencesCookieStore(mAppContext);
        BasicClientCookie cookie = new BasicClientCookie("test", "hello");
        cookie.setDomain("192.168.1.5");
        cookie.setPath("/");
        preferencesCookieStore.addCookie(cookie);

        return view;
    }

    //@ViewInject(R.id.download_addr_edit)
    //private EditText downloadAddrEdit;

    @ViewInject(R.id.download_btn)
    private Button downloadBtn;

    @ViewInject(R.id.download_page_btn)
    private Button downloadPageBtn;

    @ViewInject(R.id.result_txt)
    private TextView resultText;

    @ResInject(id = R.string.download_label, type = ResType.String)
    private String label;

    /** 移除下载 */
    @OnClick(R.id.remove_download_btn)
    public void removeDownload(View view) {
    	DownloadInfo downloadInfo = downloadManager.getDownloadInfoByAppId("520");
    	try {
    		if (downloadInfo != null) {
    			downloadManager.removeDownload(downloadInfo);
			}
        } catch (DbException e) {
            LogUtils.e(e.getMessage(), e);
        }
    }
    
   
    @OnClick(R.id.download_btn)
    public void download(View view) {
    	//下载过程中的状态监听?因为状态的切换,必然涉及UI的变化,所以需要对状态监听
    	DownloadStateListener downloadStateListener = new DownloadStateListener();
    	
    	//downManager下载的管理者对象
    	//根据一个应用的id获取一个应用的下载信息(应用当前的下载到的位置,下载应用的名称,包名,唯一性id,下载应用的总大小)
    	DownloadInfo downloadInfo = downloadManager.getDownloadInfoByAppId("520");
    	//downloadInfo是否为空???
    	if (downloadInfo == null) {
    		// 如果原来没有下载过，则开始一个新的下载
    		String target = "/sdcard/GoogleMarket88/" + "youyuan" + ".apk";
            String appUrl = "http://127.0.0.1:8090/download?name=app/com.youyuan.yyhl/com.youyuan.yyhl.apk";
            try {
                downloadManager.addNewDownload("520", appUrl,
                        "有缘网",		// 保存到数据库时候的一个应用名称
                        target,		// 指定保存路径和保存的文件名
                        true, 		// 如果目标文件存在，接着未完成的部分继续下载。服务器不支持RANGE时将从新下载。
                        false, 		// 如果从请求返回信息中获取到文件名，下载完成后自动重命名。
                        downloadStateListener);		// 用于接收下载状态的监听器
            } catch (DbException e) {
                LogUtils.e(e.getMessage(), e);
            }
		} else {
			// 如果原来下载过，则要么暂停，要继续
			HttpHandler.State state = downloadInfo.getState();
            switch (state) {
                case WAITING:
                case STARTED:
                case LOADING:
                	// 如果原来是等待、开始、正在下载，则暂停
                    try {
                        downloadManager.stopDownload(downloadInfo);	// 暂停下载
                    } catch (DbException e) {
                        LogUtils.e(e.getMessage(), e);
                    }
                    break;
                case CANCELLED://pause(暂停)
                case FAILURE:
                	// 如果原来暂停了下载，或者下载失败了，则重新下载，如果暂停的话是断点续传地下载
                    try {
                        downloadManager.resumeDownload(downloadInfo, downloadStateListener);	// 第二个参数用于接收下载状态
                    } catch (DbException e) {
                        LogUtils.e(e.getMessage(), e);
                    }
                    break;
                default:
                    break;
            }
		}
    }

    /** 下载状态监听器  */
    private class DownloadStateListener extends RequestCallBack<File> {

    	/** 下载失败 */
		@Override
		public void onFailure(HttpException arg0, String arg1) {
			refreshUI();
		}

		/** 下载成功 */
		@Override
		public void onSuccess(ResponseInfo<File> arg0) {
			refreshUI();
		}

		/** 取消下载 ,即暂停*/
		@Override
		public void onCancelled() {
			refreshUI();
		}

		/** 正在下载*/
		@Override
		public void onLoading(long total, long current, boolean isUploading) {
			refreshUI();
		}

		/** 开始下载 */
		@Override
		public void onStart() {
			refreshUI();
		}
		
    }
    
    /** 刷新UI */
    public void refreshUI() {
    	DownloadInfo downloadInfo = downloadManager.getDownloadInfoByAppId("520");
    	if (downloadInfo == null) {
			// 如果原来没有下载过，则显示成下载
    		downloadBtn.setText("下载");
    		
		}else{
			 HttpHandler.State state = downloadInfo.getState();	// 获取当前下载信息的下载状态
		        switch (state) {
		        	//1.如果状态是等待
		        	//按钮的文字显示成等待
		        
		        	//2.如过状态是开始下载
		        	//按钮的文字显示成开始下载
		        
		        	//3.如过状态是正在下载
		        	//按钮显示文字百分比进度条
		        
		        	//4.如果状态是暂停
		        	//按钮的显示文字暂停,为了提示用户可以接着下载"暂停"两个字改成"继续"
		        
		        	//5.如果状态是成功
		        	//按钮显示文字安装
		        
		        	//6.如果状态是是吧
		        	//按钮显示文字重新下载(重试)
		        
		        
		            case WAITING:
		            case STARTED:
		            case LOADING:	
		            case CANCELLED:// 如果原来是等待、开始、正在下载或者暂停的状态，则需要显示下载进度
		                if (downloadInfo.getFileLength() > 0) {
		                	// 计算下载的百分比
		                	int percent = (int) (downloadInfo.getProgress() * 100 / downloadInfo.getFileLength());
//		                    progressBar.setProgress();
		                	downloadBtn.setText(percent + "%");
		                } else {
//		                    progressBar.setProgress(0);
		                	downloadBtn.setText("0%");
		                }
		            
		                if (state == State.CANCELLED) {
							// 如果是暂停了，则显示一个"继续"
		                	downloadBtn.setText("继续");
						}
		                break;
		            case SUCCESS:
		            	downloadBtn.setText("安装");
		            	// TODO 把下载进度设置成100% progressBar.setProgress(100);
		                break;
		            case FAILURE:
		            	downloadBtn.setText("重试");
		                break;
		            default:
		                break;
		        }
		}
    	
       
    }
    
    @OnClick(R.id.download_page_btn)
    public void downloadPage(View view) {
        Intent intent = new Intent(this.getActivity(), DownloadListActivity.class);
        this.getActivity().startActivity(intent);
    }

    /////////////////////////////////////// other ////////////////////////////////////////////////////////////////

    //@OnClick(R.id.download_btn)
    public void testUpload(View view) {

        // 设置请求参数的编码
        //RequestParams params = new RequestParams("GBK");
        RequestParams params = new RequestParams(); // 默认编码UTF-8

        //params.addQueryStringParameter("qmsg", "你好");
        //params.addBodyParameter("msg", "测试");

        // 添加文件
        params.addBodyParameter("file", new File("/sdcard/test.zip"));
        //params.addBodyParameter("testfile", new File("/sdcard/test2.zip")); // 继续添加文件

        // 用于非multipart表单的单文件上传
        //params.setBodyEntity(new FileUploadEntity(new File("/sdcard/test.zip"), "binary/octet-stream"));

        // 用于非multipart表单的流上传
        //params.setBodyEntity(new InputStreamUploadEntity(stream ,length));

        HttpUtils http = new HttpUtils();

        // 设置返回文本的编码， 默认编码UTF-8
        //http.configResponseTextCharset("GBK");

        // 自动管理 cookie
        http.configCookieStore(preferencesCookieStore);

        http.send(HttpRequest.HttpMethod.POST,
                "http://192.168.1.5:8080/UploadServlet",
                params,
                new RequestCallBack<String>() {

                    @Override
                    public void onStart() {
                        resultText.setText("conn...");
                    }

                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                        if (isUploading) {
                            resultText.setText("upload: " + current + "/" + total);
                        } else {
                            resultText.setText("reply: " + current + "/" + total);
                        }
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        resultText.setText("reply: " + responseInfo.result);
                    }


                    @Override
                    public void onFailure(HttpException error, String msg) {
                        resultText.setText(msg);
                    }
                });
    }

    //@OnClick(R.id.download_btn)
    public void testGet(View view) {

        //RequestParams params = new RequestParams();
        //params.addHeader("name", "value");
        //params.addQueryStringParameter("name", "value");

        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(1000 * 10);
        http.send(HttpRequest.HttpMethod.GET,
                "http://www.baidu.com",
                //params,
                new RequestCallBack<String>() {

                    @Override
                    public void onStart() {
                        resultText.setText("conn...");
                    }

                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                        resultText.setText(current + "/" + total);
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        resultText.setText("response:" + responseInfo.result);
                    }


                    @Override
                    public void onFailure(HttpException error, String msg) {
                        resultText.setText(msg);
                    }
                });
    }

    //@OnClick(R.id.download_btn)
    public void testPost(View view) {
        RequestParams params = new RequestParams();
        params.addQueryStringParameter("method", "mkdir");
        params.addQueryStringParameter("access_token", "3.1042851f652496c9362b1cd77d4f849b.2592000.1377530363.3590808424-248414");
        params.addBodyParameter("path", "/apps/测试应用/test文件夹");

        HttpUtils http = new HttpUtils();
        http.send(HttpRequest.HttpMethod.POST,
                "https://pcs.baidu.com/rest/2.0/pcs/file",
                params,
                new RequestCallBack<String>() {

                    @Override
                    public void onStart() {
                        resultText.setText("conn...");
                    }

                    @Override
                    public void onLoading(long total, long current, boolean isUploading) {
                        resultText.setText(current + "/" + total);
                    }

                    @Override
                    public void onSuccess(ResponseInfo<String> responseInfo) {
                        resultText.setText("upload response:" + responseInfo.result);
                    }

                    @Override
                    public void onFailure(HttpException error, String msg) {
                        resultText.setText(msg);
                    }
                });
    }

    // 同步请求 必须在异步块儿中执行
    private String testGetSync() {
        RequestParams params = new RequestParams();
        params.addQueryStringParameter("wd", "lidroid");

        HttpUtils http = new HttpUtils();
        http.configCurrentHttpCacheExpiry(1000 * 10);
        try {
            ResponseStream responseStream = http.sendSync(HttpRequest.HttpMethod.GET, "http://www.baidu.com/s", params);
            //int statusCode = responseStream.getStatusCode();
            //Header[] headers = responseStream.getBaseResponse().getAllHeaders();
            return responseStream.readString();
        } catch (Exception e) {
            LogUtils.e(e.getMessage(), e);
        }
        return null;
    }
}
